import React, { useEffect, useState } from 'react';
import "./style.scss";
let wss;
// 定义一个名为ServerChat的函数组件
const ServerChat = () => {
  const user_id = 1;
  const server_id = 564564;
  const [list, setList] = useState([]);
  const [message, setMessage] = useState([])

  const onKeyDown = (e) => {
    // if (e.keyCode === 13) {
      wss.send(
        JSON.stringify({
          type: 'addMessage',
          data: {
            user_id,
            server_id,
            message: message,
            dir: 1
          },
        })
      );
    // }
  };
  useEffect(() => {
    const ws = new WebSocket(
      `ws://124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    );

    wss = ws;

    ws.addEventListener('open', () => {
      console.log('WebSocket连接已打开');
      ws.send(
        JSON.stringify({
          type: 'getChatList',
          data: {
            user_id,
            server_id,
          },
        })
      );
    });

    ws.addEventListener('message', (res) => {
      console.log('服务器消息', JSON.parse(res.data));
      const { type, data } = JSON.parse(res.data);
      if (type === 'getChatList') {
        setList(data);
      } else if (type === 'addMessage') {
        setList((prev) => [...prev, data]);
      }
    });
  }, []);

  // 返回一个包含ServerChat文本的div元素
  return (
    <div className="chat">
    <div className="title">张三</div>
    <div className="chat-list">
      {list.map((v, i) => {
        const clsssNameParams = "chat-list-item-" + (v.dir === 1 ? "right" : "left")
        const avatarUrl = v.dir === 1 ? v.user_avatar : v.server_avatar
        return (
          <div
            className={clsssNameParams}
            key={i}
          >
            <div className="avatar">
              <img
                src={avatarUrl}
                alt=""
              />
            </div>
            <div className="content">
              <div className="text">
                {v.message}
              </div>
              <div className="image"></div>
              <div className="video"></div>
            </div>
          </div>
        );
      })}
    </div>
    <div className="opration">
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
      />
      <button className="submit" onClick={() => onKeyDown()}>
        发送
      </button>
    </div>
  </div>
  );
};

export default ServerChat;
